package com.fary.context.support;

import com.fary.context.MessageSource;
import com.fary.context.MessageSourceResolvable;
import com.fary.context.i18n.LocaleContextHolder;
import com.fary.core.SpringException;

import java.util.Locale;

public class MessageSourceAccessor {

	private final MessageSource messageSource;

	private final Locale defaultLocale;

	public MessageSourceAccessor(MessageSource messageSource) {
		this.messageSource = messageSource;
		this.defaultLocale = null;
	}

	public MessageSourceAccessor(MessageSource messageSource, Locale defaultLocale) {
		this.messageSource = messageSource;
		this.defaultLocale = defaultLocale;
	}

	protected Locale getDefaultLocale() {
		return (this.defaultLocale != null ? this.defaultLocale : LocaleContextHolder.getLocale());
	}

	public String getMessage(String code, String defaultMessage) {
		String msg = this.messageSource.getMessage(code, null, defaultMessage, getDefaultLocale());
		return (msg != null ? msg : "");
	}

	public String getMessage(String code, String defaultMessage, Locale locale) {
		String msg = this.messageSource.getMessage(code, null, defaultMessage, locale);
		return (msg != null ? msg : "");
	}

	public String getMessage(String code, Object[] args, String defaultMessage) {
		String msg = this.messageSource.getMessage(code, args, defaultMessage, getDefaultLocale());
		return (msg != null ? msg : "");
	}

	public String getMessage(String code, Object[] args, String defaultMessage, Locale locale) {
		String msg = this.messageSource.getMessage(code, args, defaultMessage, locale);
		return (msg != null ? msg : "");
	}

	public String getMessage(String code) throws SpringException {
		return this.messageSource.getMessage(code, null, getDefaultLocale());
	}

	public String getMessage(String code, Locale locale) throws SpringException {
		return this.messageSource.getMessage(code, null, locale);
	}

	public String getMessage(String code, Object[] args) throws SpringException {
		return this.messageSource.getMessage(code, args, getDefaultLocale());
	}

	public String getMessage(String code, Object[] args, Locale locale) throws SpringException {
		return this.messageSource.getMessage(code, args, locale);
	}

	public String getMessage(MessageSourceResolvable resolvable) throws SpringException {
		return this.messageSource.getMessage(resolvable, getDefaultLocale());
	}

	public String getMessage(MessageSourceResolvable resolvable, Locale locale) throws SpringException {
		return this.messageSource.getMessage(resolvable, locale);
	}

}